<template>
	<view class="wrap">
		<!-- <view class="tab_box flex_sa">
			<view class="tab_item flex_c" :class="{active:tabCurrent==index}" v-for="(item,index) in tabList"
				:key="index" @click="changeTab(index)">
				{{item.name}}
			</view>
		</view> -->
		<!-- <view class="time_box" v-if="tabCurrent==3">
			<uni-datetime-picker v-model="range" type="daterange" @change="changeHandler">
				{{range.join('/')}} <text class="iconfont icon-xiangxia"></text>
			</uni-datetime-picker>

		</view> -->
		<view class="table_box">
			<uni-table ref="table" :loading="loading" border stripe emptyText="暂无更多数据"
				@selection-change="selectionChange">
				<uni-tr>
					<uni-th width="10" align="center">
						<view class="table_th">
							文件
						</view>
					</uni-th>
					<uni-th width="20" align="center">
						<view class="table_th">
							状态
						</view>
					</uni-th>
					<uni-th width="30" align="center">
						<view class="table_th">
							操作
						</view>
					</uni-th>
				</uni-tr>

				<uni-tr v-for="(item, index) in tableData" :key="index">
					<uni-td align="center" width="100">
						<view class="table_td url_td line2" v-if="item.pdf_url">{{ item.pdf_url }}</view>
						<view class="table_td url_td line2" v-else>{{ item.title }}</view>
					</uni-td>
					<uni-td align="center">
						<view class="table_td" v-if="item.status">已完成</view>
						<view class="table_td" v-else>生成中</view>
					</uni-td>
					<uni-td align="center">
						<view class="action_box flex_sb" :class="{'gray':!item.pdf_url}">
							<view class="action_item" @click="previewFile(item.pdf_url)">预览</view>
							<view class="action_item" @click="actionSheetTap(item.pdf_url)">分享</view>
							<view class="action_item" @click="openEmailHandler(item)">邮箱</view>
						</view>

					</uni-td>

				</uni-tr>
			</uni-table>
		</view>
		<uni-popup ref="wordPrint" type="center" :animation="false" :mask-click="false">
			<view class="pop_wordPrint">
				<!-- 				<view class="title_box">
					设置字印
				</view> -->
				<view class="input_box">
					<input type="text" v-model="emailInfo.send_email" placeholder="请输入邮箱" />
				</view>
				<view class="footer_box flex_sb">
					<view class="left flex_c" @click="closeEmailHandler">
						取消
					</view>
					<view class="right flex_c" @click="setEmailHandler">
						发送
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		debounceImmediate
	} from "@/utils/validate";
	import {
		exportList,
		statement_export,
		sendemail
	} from "@/api/new_api.js"
	export default {
		data() {
			return {
				tabCurrent: 0,
				tabList: [{
					name: '今天',
					id: 'today'
				}, {
					name: '本周',
					id: 'nowweek'
				}, {
					name: '本月',
					id: 'nowmonth'
				}, {
					name: '自定义',
					id: 1
				}],
				tableData: [],
				range: [],
				infoData: {},
				page: 1,
				limit: 20,
				loadend: false, //是否加载完毕
				loading: false, //是否加载中
				outputUrl: '',
				keyLock: false,
				schedule: 0, //下载进度1-100%
				filePath: '',
				emailInfo: {
					id: '',
					send_email: ''
				}

			}
		},
		onReachBottom() {
			if (this.loadend) return;
			if (this.loading) return;
			this.page++;
			this.initData()
		},
		onLoad() {
			console.log(wx.env.USER_DATA_PATH, "路径");
			this.range = this.getCurrentDateRange()
			this.initData()
		},
		methods: {
			closeEmailHandler() {
				this.$refs.wordPrint.close()
			},
			// 打开发送邮箱弹窗
			openEmailHandler(item) {
				this.emailInfo.id = item.id
				this.$refs.wordPrint.open()
			},
			setEmailHandler: debounceImmediate(function() {
				let that = this
				if (!this.emailInfo.send_email) return this.$util.Tips({
					title: '请输入邮箱'
				})
				uni.showLoading()
				sendemail(this.emailInfo).then((res) => {
					const data = res.data
					if (data.success == false) {
						return this.$util.Tips({
							title: data.message
						})
					} else {
						that.closeEmailHandler()
						this.$util.Tips({
							title: data.message
						})
					}


				}).catch(() => {
					uni.hideLoading()
				})
			}),
			// 获取当前时间，文件命名
			generateTimestampFileName() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');

				return `${year}${month}${day}${hours}${minutes}${seconds}`;
			},
			async actionSheetTap(url) {
				if (!url) return
				uni.showLoading({
					title: "加载中...",
					mask: true
				})
				const that = this
				await this.downLoadFileHandler(url)
				uni.showActionSheet({
					itemList: ['分享到好友', '添加到收藏'],
					success: e => {
						if (e.tapIndex == 0) {
							uni.shareFileMessage({
								filePath: that.filePath,
								fileName: `${that.generateTimestampFileName()}.xlsx`,
								success(res) {
									console.log(res, "分享成功")
								},
								fail: console.error
							})
						} else {
							uni.addFileToFavorites({
								filePath: that.filePath,
								fileName: `${that.generateTimestampFileName()}.xlsx`,
								success(res) {
									console.log(res, "收藏成功")
								},
								fail: console.error
							})
						}
					}
				});

			},

			// 预览图片和文件成功
			async previewFile(url) {
				console.log(url, "----");
				if (!url) return
				// 流程步骤: 利用下载文件功能 先生成临时文件 - 调用api打开临时文件里面的内容,从而生成预览的效果,但是这个未能真实的下载到本地
				// 1.pdfUrl  可以直接在浏览器打开  2.一定要在小程序后台配置该pdf的域名 让其可以下载
				uni.showLoading({
					title: '加载中...'
				})
				let that = this
				this.schedule = 0; //载入进度为0
				await this.downLoadFileHandler(url)
				//  文件打开文件预览
				console.log(that.filePath);
				uni.openDocument({
					filePath: encodeURI(that.filePath),
					showMenu: true,
					fileType: 'xlsx',
					success: function(res) {
						uni.hideLoading();
					},
					fail: function(err) {
						uni.hideLoading();
						uni.showToast({
							title: '打开失败',
							duration: 1500,
							icon: 'none'
						});
						console.log('打开失败');
					}
				});
			},
			downLoadFileHandler(url) {
				let that = this
				return new Promise((resolve, reject) => {
					const downloadTask = uni.downloadFile({
						url: url, // 图片或者文件地址
						filePath: `${wx.env.USER_DATA_PATH}/${that.generateTimestampFileName()}.xlsx`,
						success: function(res) {
							that.filePath = res.filePath; // 临时文件存储路径
							resolve(res.filePath)

						},
						fail: function(err) {
							console.log('下载失败原因', err);
							that.$util.Tips({
								title: err
							})
							reject(err)
						},
						complete() {
							uni.hideLoading()
						}
					});
					downloadTask.onProgressUpdate(res => {
						console.log('下载进度' + res.progress);
						this.schedule = res.progress
						console.log('下载进度：' + res.progress);
						console.log('已下载长度：' + res.totalBytesWritten);
						console.log('文件总长度：' + res.totalBytesExpectedToWrite);
					});
				})
			},
			clearData() {
				this.page = 1
				this.loading = false
				this.loadend = false
				this.tableData = []
				this.outputUrl = ""
			},
			initData() {

				this.exportList()

			},
			exportList() {

				this.loading = true;
				const parmas = {
					page: this.page,
					limit: this.limit,
				}
				exportList(parmas).then((res) => {
					// let list = []
					// for (var index = 0; index < 50; index++) {
					// 	list.push(...res.data.list)

					// }
					let list = res.data.list || []
					this.loadend = list.length < this.limit
					this.tableData = this.tableData.concat(list)
					this.infoData = res.data
					this.loading = false;


				}).catch(err => {
					this.loading = false;
				});
			},
			statement_export() {
				console.log(11111111111111);
				let that = this
				const parmas = {
					page: this.page,
					limit: this.limit,
					day_type: this.tabList[this.tabCurrent].id,
					search_time_str: this.range[0],
					search_time_end: this.range[1]
				}
				return statement_export(parmas).then((res) => {
					this.keyLock = false
					const data = res.data
					this.outputUrl = data.url
					if (!this.outputUrl) return this.$util.Tips({
						title: '导出链接为空'
					})
					// uni.setClipboardData({
					// 	data: this.outputUrl,
					// 	success: () => {
					// 		that.$util.Tips({
					// 			title: '链接已复制,请在浏览器中打开',
					// 			endtime: 2000
					// 		})
					// 	}
					// })
				}).catch(() => {
					this.keyLock = false
				})
			},
			getCurrentDateRange() {
				const today = new Date();

				// 获取年、月、日
				const year = today.getFullYear();
				const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
				const day = String(today.getDate()).padStart(2, '0');

				// 当前日期字符串
				const currentDate = `${year}-${month}-${day}`;

				return [currentDate, currentDate];
			},
			changeTab(e) {
				if (this.tabCurrent == e) return
				this.tabCurrent = e
				this.clearData()
				this.initData()
			},

			changeHandler(e) {
				this.clearData()
				this.initData()
				console.log('changeHandler事件:', e);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.pop_wordPrint {
		width: 540rpx;
		// height: 300rpx;
		border-radius: 20rpx;
		background: #FFFFFF;
		padding-top: 30rpx;

		.title_box {
			text-align: center;
			color: #3D3D3D;
			font-size: 32rpx;
			margin-bottom: 15rpx;
			line-height: 50rpx;
		}

		.input_box {
			width: 472rpx;
			// height: 89rpx;
			padding: 24rpx 0;
			margin: 0 auto;
			text-align: center;
			border-radius: 12rpx;
			background: #F5F6F7;
			font-size: 28rpx;
			margin-bottom: 25rpx;
		}

		.footer_box {
			height: 99rpx;
			border-top: 2rpx solid #F2F2F2;
			font-size: 34rpx;
			font-weight: 500;
			text-align: center;

			.left {
				height: 100%;
				flex: 1;
				color: #868D9E;
			}

			.right {
				height: 100%;
				position: relative;
				flex: 1;
				color: #000;

				&::before {
					position: absolute;
					left: 0;
					top: 0;
					content: "";
					height: 100%;
					width: 2rpx;
					background: #F2F2F2;
				}
			}
		}
	}

	.loading_box {
		text-align: center;
	}

	::v-deep .uni-table {
		.table--border {
			border: none;
		}

		// 改表头字体样式
		border: none;

		.uni-table-th {
			border-right: none;
			background: #F4F5F6;
			font-size: 24rpx;
			font-weight: normal;
			color: #9E9E9E;
			border: none;
		}
	}

	.url_td {
		// width: 300rpx;
		word-wrap: break-word;
		word-break: break-all;
	}

	.table_td {

		// white-space: nowrap;
		font-size: 26rpx;
		color: #363636;
	}

	.wrap {
		padding-bottom: 50rpx;

		.footer {
			background: #fff;
			width: 100%;
			position: fixed;
			left: 0;
			bottom: 0;
			padding-bottom: 50rpx;
			border: 1rpx solid #E5E5E5;

			.top_box {
				padding: 25rpx 30rpx;
				border-bottom: 2rpx solid #F4F5F6;

				.left_box {
					font-size: 26rpx;
					color: #737272;

					text {
						color: #D43030;
					}
				}

				.btn_box {

					.btn_item {
						padding: 15rpx 30rpx;
						color: #fff;
						font-size: 30rpx;
						background: #43CF7C;
						border-radius: 11rpx;
						margin-left: 10rpx;
					}
				}

				.gray_btn {
					background: #ccc;
				}

			}

			.btm_box {
				padding: 20rpx 0;

				.item_box {
					position: relative;
					text-align: center;
					flex: 1;

					&:not(:first-child)::before {
						position: absolute;
						left: 0;
						top: 50%;
						transform: translateY(-50%);
						content: "";
						width: 1rpx;
						height: 80rpx;
						background: #E5E5E5;
					}

					.text1 {
						color: #737272;
						margin-bottom: 5rpx;
					}

					.text2 {
						color: #424040;
					}
				}
			}
		}

		.time_box {
			font-size: 30rpx;
			color: #000;
			margin: 30rpx 0;
			padding-left: 30rpx;

			.iconfont {
				margin-left: 10rpx;
				font-size: 26rpx;
				font-weight: bold;
			}
		}

		.tab_box {
			position: sticky;
			top: 0;
			z-index: 10;
			width: 100%;
			height: 76rpx;
			// padding: 0 150rpx;
			background: #FFF;

			.tab_item {
				font-size: 34rpx;
				height: 100%;
				color: #383838;
				border-bottom: 6rpx solid transparent;

			}

			.active {
				color: #643400;
				border-bottom: 6rpx solid #643400;
			}

		}

		.table_box {
			width: 100%;

			.action_box {
				color: rgb(60, 156, 255);

				.action_item {


					&:not(:last-child) {
						margin-right: 10rpx;
					}
				}
			}

			.gray {
				color: #ccc !important;
			}
		}
	}

	.content_box {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		border-radius: 20rpx;
		color: #000;
		background: #fff;
		font-size: 40rpx;
		padding: 20rpx 30rpx;
		text-align: center;
	}
</style>